package com.jianxiu.web;

import java.io.IOException;
import java.util.Map;
import java.util.Objects;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.jianxiu.bean.Cons;
import com.jianxiu.config.SysConf;
import com.jianxiu.utils.WeixinTools;
import com.jianxiu.utils.XmlUtils;

/**
 * Created by tancw on 2016/10/8.
 */
@Controller
public class WeixinServelt {

    public static String DEFAULT_MSG = "智能报修";

    @RequestMapping(value = "weixin.page", method = RequestMethod.GET)
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        try {
            request.setCharacterEncoding(Cons.UTF_8);
            response.setCharacterEncoding(Cons.UTF_8);
            String signature = Objects.requireNonNull(request.getParameter("signature"));
            String timestamp = Objects.requireNonNull(request.getParameter("timestamp"));
            String nonce = Objects.requireNonNull(request.getParameter("nonce"));
            String echostr = Objects.requireNonNull(request.getParameter("echostr"));

            if (WeixinTools.access(SysConf.get("weixin.token"), signature, timestamp, nonce)) {
                response.getWriter().write(echostr);
            }
        } catch (NullPointerException e) {
            response.getWriter().write("参数错误");
            return;
        }
    }

    @RequestMapping(value = "weixin.page", method = RequestMethod.POST)
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws Exception {
        request.setCharacterEncoding(Cons.UTF_8);
        response.setCharacterEncoding(Cons.UTF_8);
//        String accessToken = TokenUtil.getToken(false);
        Map<String, String> requestMap = XmlUtils.toMap(request.getInputStream());
        String fromUser = requestMap.get("FromUserName");
        String toUser = requestMap.get("ToUserName");
        String messageType = requestMap.get("MsgType");
        String defaultContent = DEFAULT_MSG;
        String returnMsg = "success";
        if (StringUtils.equals("event", messageType)) {
            if (StringUtils.equals("subscribe", requestMap.get("Event"))) {
                response.getWriter().write("success");
                return;
            }
            String content = DEFAULT_MSG;
            returnMsg = getReturnMsg(fromUser, toUser, content);
        } else if (StringUtils.equals("text", messageType)) {
            String content = DEFAULT_MSG;
            if (StringUtils.isBlank(content)) content = defaultContent;
            returnMsg = getReturnMsg(fromUser, toUser, content);
        }
        response.getWriter().write(returnMsg);
    }

    public String getReturnMsg(String toUser, String fromUser, String content) {
        StringBuffer str = new StringBuffer();
        str.append("<xml>");
        str.append("<ToUserName><![CDATA[" + toUser + "]]></ToUserName>");
        str.append("<FromUserName><![CDATA[" + fromUser + "]]></FromUserName>");
        str.append("<CreateTime>" + System.currentTimeMillis() / 1000 + "</CreateTime>");
        str.append("<MsgType><![CDATA[text]]></MsgType>");
        str.append("<Content><![CDATA[" + content + "]]></Content>");
        str.append("</xml>");
        System.out.println(str.toString());
        return str.toString();
    }


}
